// 控制器，处理请求参数，调用业务逻辑接口执行处理，返回结果
package controllers

import (
	"api/services"
	"fmt"
	"github.com/labstack/echo"
)

// ...

// 注册用户控制器接收参数结构
type RegisterAccountParams struct {
	username string `valid:"matches(^\w{3,20}$)"`
	password string `valid:"stringlength(4|20)"`
	nickname string `valid:"stringlength(3|20)"`
	gender   string `valid:"matches(^(?m|f))$)"`
	mobile   string `valid:"matches(^\d{11}$),optional"`
}

// 注册用户控制器
func RegisterAccount(c echo.Context) (err error) {
	// 获取参数并验证合法性
	params := RegisterAccountParams{
		username: c.FormValue("username"),
		password: c.FormValue("password"),
		nickname: c.FormValue("nickname"),
		gender:   c.FormValue("gender"),
		mobile:   c.FormValue("mobile"),
	}
	if _, err := valid.ValidateStruct(params); err != nil {
		return services.NewError(services.ErrCodeInvalidParams, err.Error())
	}

	// 调用service方法
	err, u := services.CreateUser(&services.User{
		Username: params.username,
		Password: params.password,
		Nickname: params.nickname,
		Gender:   params.gender,
		Mobile:   params.mobile,
	})
	if err != nil {
		fmt.Println("create user", err)
		return err
	}

	// 响应结果
	return responseJSON(c, response{
		data: map[string]interface{}{
			"user": u,
		},
	})
}

// ...
